package core;

import java.io.*;
import java.util.*;

public class SetIndex extends Index {
	
//	public static final String INDEX_FILE = "data/sets.dat";
	private static final long serialVersionUID = -979339446130937115L;
	
	private ArrayList<SetRecord> records;
	
	public SetIndex() {
		super(Preferences.SET_INDEX_FILE);
		records = new ArrayList<SetRecord>();
		setDisplayCols(SetRecord.NUM_FIELDS);
	}
	
	public void add(SetRecord sr) {
		records.add(sr);
		fireTableStructureChanged();
		save();
	}
	public SetRecord get(int i) {
		return records.get(i);
	}
	public void remove(int i) {
		fireTableRowsDeleted(i, i);
		records.remove(i);
		save();
	}
	public SetRecord newRecord() {
		SetRecord sr = new SetRecord(nextId());
		return sr;
	}
	
	public String toString() {
		return "SetIndex: " + records.toString();
	}
	
	/*public void save() {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream(indexFile));
			oos.writeObject(records);
			oos.writeObject(nextId);
			oos.close();
			
		} catch(IOException ex) {
			ex.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public static SetIndex load(File f) {
		if(!f.exists())
			return null;
		
		SetIndex ind = new SetIndex();
		try {
			ObjectInputStream ois = new ObjectInputStream(
					new FileInputStream(f));
			ind.records = (ArrayList<SetRecord>)ois.readObject();
			ind.nextId = (Integer)ois.readObject();
			ois.close();
			
		} catch(IOException ex) {
			ex.printStackTrace();
		} catch(ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		
		return ind;
	}*/
	
	// Serialization methods
	protected void writeObject(ObjectOutputStream out) throws IOException {
		super.writeObject(out);
		out.writeObject(records);
	}
	@SuppressWarnings("unchecked")
	protected void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		super.readObject(in);
		this.records = (ArrayList<SetRecord>)in.readObject();
	}
	public static SetIndex load(File file) {
		if(!file.exists())
			return null;
		
		SetIndex index = new SetIndex();
		Index.load(index, file);
		return index;
	}
	
	
	// TableModel
	public int getRowCount() {
		return records.size();
	}
	public String getColumnName(int column) {
		return SetRecord.fieldNames[column];
	}
	public Class<?> getColumnClass(int columnIndex) {
		if (columnIndex == SetRecord.DATE)
			return Date.class;
		else
			return String.class;
	}
	public Object getValueAt(int rowIndex, int columnIndex) {
		return records.get(rowIndex).getField(columnIndex);
	}
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		records.get(rowIndex).setField(columnIndex, aValue);
	}
}
